package chapter01;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class ThreeSum {
    //双指针
    public List<List<Integer>> threeSum(int[] nums) {
        int length=nums.length;
        List<List<Integer>> lists=new LinkedList<>();
        if(length<3){
            return lists;
        }
        Arrays.sort(nums);
        for (int i=0;i<length;i++){
            if(i>0&&nums[i]==nums[i-1]){
                continue;
            }
            int start=i+1,end=length-1;
            while(start<end){
                if(nums[i]+nums[start]+nums[end]==0) {
                    List<Integer> list=new LinkedList<>();
                    list.add(nums[i]);
                    list.add(nums[start]);
                    list.add(nums[end]);
                    lists.add(list);
                    while(start<end&&nums[start]==nums[start+1]){
                        start++;
                    }
                    start++;
                    while (start<end&&nums[end]==nums[end-1]){
                        end--;
                    }
                    end--;

                }else if(nums[i]+nums[start]+nums[end]<0){
                    start++;
                }else{
                    end--;
                }
            }
        }
        return lists;
    }

    public static void main(String[] args) {
        System.out.println(new ThreeSum().threeSum(new int[]{-1,0,1,2,-1,-4}));
    }
}
